<template>
  <base-breadcrumb :title="$route.meta.title" :breadcrumb="!isAudit">
    <!-- 样板工程实施计划编辑 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel != 0 ? rules : {}"
      id="base-breadcrumb"
      style="position: relative"
    >
      <a-spin :spinning="loading[0] || loading[1]">
        <!-- 项目信息 -->
<!--        @projectchange="handleChange"-->
        <base-info
          ref="baseInfo"
          :disabled="form.planItems.length > 1 || editModel=='0'"
          :form="form"
          :editModel="editModel"
          :isNeedAuth="true"
          @companychange="companychange"
        />
        <!-- 表格 -->
        <a-card :bordered="false" style="margin-bottom: 80px">
          <title-name title="样板工程实施计划"></title-name>
          <list-table
            ref="table"
            :isShowCountBar="false"
            :selectConfig="{ use: editModel == 0, type: 'checkbox', rowKey: 'id' }"
            :exportConfig="{ use: editModel == 0, select: '样板工程实施计划', all: '样板工程实施计划' }"
            :exportConfigText="editModel == 0 ? { select: '选中导出', all: '全部导出' } : null"
            :scroll="{ x: 1600 }"
            :showPage="false"
            :columns="columns"
            :request="loadData"
          >
            <a-button
              slot="prefix"
              v-if="editModel != 0"
              :disabled="form.projectId ? false : true"
              type="primary"
              icon="plus"
              @click="handleAdd"
              >添加计划项</a-button
            >
            <!-- 样板部位 -->
            <template slot="part" slot-scope="text, record">
              <span v-if="editModel == 0 || record.whetherEdit == 0">{{ text }}</span>
              <BaseInput v-else placeholder="请输入样板部位" v-model="record.part" />
            </template>
            <!-- 样板名称 -->
            <template slot="name" slot-scope="text, record">
              <span v-if="editModel == 0 || record.whetherEdit == 0">{{ text }}</span>
              <BaseInput v-else placeholder="请输入样板名称" v-model="record.name" />
            </template>
            <!-- 劳务单位 -->
            <template slot="subcontractorId" slot-scope="text, record">
              <span v-if="editModel == 0 || record.whetherEdit == 0">{{ record.subcontractor }}</span>
              <template v-else>
                <SelectSubcontractor
                  v-if="record.isFirst"
                  placeholder="请选择劳务单位"
                  :projectId="form.projectId"
                  showSearch
                  :list.sync="subcontractorList"
                  v-model="record.subcontractorId"
                  @select="$set(record, 'monitorId', '')"
                  :extraSubcontractor="{
                    subContractorId: '-1',
                    name: '分包单位未进场'
                  }"
                />
                <a-select v-else v-model="record.subcontractorId" placeholder="请选择劳务单位">
                  <a-select-option
                    v-for="item in subcontractorList"
                    :value="item.subContractorId"
                    :key="item.subContractorId"
                    >{{ item.name }}</a-select-option
                  >
                </a-select>
              </template>
            </template>
            <!-- 班组 -->
            <template slot="monitorId" slot-scope="text, record">
              <span v-if="editModel == 0 || record.whetherEdit == 0">{{ record.monitor }}</span>
              <template v-else>
                <!-- v-if="index == 0" -->
                <SelectTeam
                  v-if="record.subcontractorId != '-1'"
                  placeholder="请选择班组"
                  showSearch
                  :form="record"
                  :keyValue="['projectId', 'subcontractorId']"
                  v-model="record.monitorId"
                />
                <a-select v-else defaultValue="-1" placeholder="请选择班组">
                  <a-select-option value="-1" key="-1">分包单位未进场</a-select-option>
                </a-select>
              </template>
            </template>
            <!-- 计划制作时间 -->
            <template slot="makeDate" slot-scope="text, record">
              <span v-if="editModel == 0 || record.whetherEdit == 0">{{ text }}</span>
              <a-date-picker v-else placeholder="请选择制作时间" valueFormat="YYYY-MM-DD" v-model="record.makeDate" />
            </template>
            <!-- 实施要点 -->
            <template slot="implPoints" slot-scope="text, record">
              <span v-if="editModel == 0 || record.whetherEdit == 0">{{ text }}</span>
              <BaseInput :maxLength="300" v-else placeholder="请输入实施要点" v-model="record.implPoints" />
            </template>
            <template v-if="record.whetherEdit == 1 || !record.id" slot="actions" slot-scope="text, record">
              <!-- <template v-if="!record.isEdit">
                <a @click="record.isEdit = true">编辑</a>
                <a-divider type="vertical"></a-divider>
              </template> -->
              <!-- 删除 -->
              <a @click="handleDelete(record)">删除</a>
            </template>
          </list-table>
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div
      v-if="!isConsultation"
        class="btn_box page-btn-right-top"
      >
        <a-button
          :disabled="loading[0] || loading[1]"
          v-if="editModel == 1 && statusCode === '0' && form.version && form.version <= 1"
          type="danger"
          class="button_right"
          @click="handleRemove"
          >删除草稿</a-button
        >
        <a-button
          :loading="loading[0]"
          :disabled="loading[1]"
          v-if="((editModel == 1 || editModel == 3) && (statusCode === '0' || statusCode === '3' || statusCode === '2')) || editModel == 2"
          type="primary"
          class="button_right"
          @click="handleSubmit(0)"
          >{{  statusCode === '3' || form.version > 1 ? '保存' : '保存草稿' }}</a-button
        >
        <a-button
          :loading="loading[1]"
          :disabled="loading[0]"
          v-if="
            (editModel == 1 && (statusCode === '0' || statusCode === '3')) ||
            editModel == 2 ||
            (editModel != 0 && statusCode === '2')
          "
          type="primary"
          class="button_right"
          @click="handleSubmit(1)"
          >提交</a-button
        >
        <a-button v-if="checkVisibleInDetail" type="primary" @click="handleActiveClose">关闭</a-button>
      </div>
    </a-form-model>
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { projectImplementationPlan } from '@/api/quality/sample' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import BaseInfo from '@/components/businessComponents/BaseInfo' // 基础信息
import SelectSubcontractor from '@/components/Select/SelectSubcontractor' // 分包商
import SelectTeam from '@/components/Select/SelectTeam' // 班组
// import { STable } from '@/components' // 表格

export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    BaseInfo,
    // STable,
    SelectSubcontractor,
    SelectTeam
  },
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: { 0: false, 1: false },
      editModel: 0,
      id: '',
      form: {
        planItems: []
      }, // 表单
      subcontractorList: [], // 劳务单位模板
      statusCode: '', // 审批状态
      loadData: () => {
        return Promise.resolve({
          code: 200,
          data: this.filterList,
          total: this.filterList?.length || 0,
          totalSize: this.filterList?.length || 0
        })
      },
      rules: {
        branchCompanyId: [{ required: true, message: '请选择分公司', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
        part: [{ required: true, whitespace: true, message: '请输入样板部位', trigger: 'change' }],
        name: [{ required: true, whitespace: true, message: '请输入样板名称', trigger: 'change' }],
        makeDate: [{ required: true, message: '请选择计划制作时间', trigger: 'change' }],
        subcontractorId: [{ required: true, message: '请选择劳务单位', trigger: 'change' }],
        monitorId: [{ required: true, message: '请选择班组', trigger: 'change' }],
        implPoints: [{ required: true, whitespace: true, message: '请输入样板实施要点 ', trigger: 'change' }]
      },
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  computed: {
    // 筛选需要显示的计划项
    filterList() {
      return this.form.planItems?.filter((i) => !i.hidden)
    },
    // 表头
    columns() {
      let columns = [
        {
          title: '序号',
          width: 80,
          dataIndex: 'number',
          customRender() {
            return arguments[2] + 1
          }
        },
        {
          title: '样板部位',
          dataIndex: 'part',
          width: 220,
          scopedSlots: { customRender: 'part' }
        },
        {
          title: '样板名称',
          dataIndex: 'name',
          width: 220,
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '劳务单位',
          dataIndex: this.editModel == 0 ? 'subcontractor' : 'subcontractorId',
          width: 220,
          scopedSlots: { customRender: 'subcontractorId' }
        },
        {
          title: '班组',
          dataIndex: this.editModel == 0 ? 'monitor' : 'monitorId',
          width: 220,
          scopedSlots: { customRender: 'monitorId' }
        },
        {
          title: '计划制作时间',
          dataIndex: 'makeDate',
          width: 220,
          scopedSlots: { customRender: 'makeDate' }
        },
        {
          title: '实施要点',
          dataIndex: 'implPoints',
          width: 220,
          scopedSlots: { customRender: 'implPoints' }
        },
        this.editModel == 0
          ? {
              title: '实际实施时间',
              width: 180,
              dataIndex: 'constructionDate'
            }
          : {
              title: '操作',
              dataIndex: 'actions',
              width: 180,
              fixed: 'right',
              align: 'center',
              scopedSlots: { customRender: 'actions' }
            }
      ] // 表头
      return columns
    }
  },
 async mounted() {
    this.$route.meta.title = [
      '样板工程实施计划查看',
      '样板工程实施计划编辑',
      '样板工程实施计划添加',
      '样板工程实施计划更新'
    ][this.editModel]
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.loading[0] = true
      let args = {}
      if (this.businessId) {
        args.businessId = this.businessId
      } else {
        args.id = this.id
      }
      args.isView = 0
      this.historyId && (args.historyId = this.historyId)
      projectImplementationPlan
        .getDetail(args)
        .then((res) => {
          this.loading[0] = false
          if (res.code === 200) {
            // 添加行标识
            let hasFirst = true
            for (let index in res.data.planItems) {
              let item = res.data.planItems[index]
              if (hasFirst && item.whetherEdit != 0) {
                item.isFirst = true
                hasFirst = false
              }
              item.key = 'row' + index
              item.projectId = res.data.projectId
            }
            this.form = res.data
            this.statusCode = res.data.statusCode
            this.$nextTick(() => {
              this.$refs.table?.getData(null, true)
            })
          }
        })
        .catch((res) => {
          this.loading[0] = false
        })
    }
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('quality_sample_project_plan')
  },
  methods: {
    /**
     * 新增计划项
     */
    handleAdd() {
      let obj = {
        key: `row${this.form.planItems.length + 1}`,
        isEdit: true,
        projectId: this.form.projectId
      }
      if (
        (this.form.planItems.length > 0 && !this.form.planItems[this.form.planItems.length - 1].isFirst) ||
        this.form.planItems.length === 0
      ) {
        obj.isFirst = true
      }
      this.form.planItems.push(obj)
      this.$refs.table.getData(null, true)
    },
    companychange(branchCompanyId) {
      this.form.branchCompanyId = branchCompanyId
      if (this.editModel == '2') {
        this.handleChange()
      }
    },
    /**
     * 项目改变时
     */
    handleChange() {
      for (let index in this.form.planItems) {
        let item = this.form.planItems[index]
        item.projectId = this.form.projectId
        if (item.subcontractorId) { //不知道为什么要清空，导致出现编辑不切换项目，清空
          //item.subcontractorId = ''
        } else {
          this.$set(this.form, 'subcontractorId', '')
          this.$set(this.form, 'subcontractor', '')
        }
        if (item.monitorId) {
          //item.monitorId = ''
        } else {
          this.$set(this.form, 'monitorId', '')
          this.$set(this.form, 'monitor', '')
        }
      }
    },
    /**
     * @description: 删除计划项
     * @param {*} record：计划项对象
     * @return {*}
     */
    handleDelete(record) {
      this.$confirm({
        title: '温馨提示',
        content: '确定删除计划项？',
        onOk: () => {
          this.form.planItems = this.form.planItems.filter((i) => i.key !== record.key)
          this.$refs.table.getData(null, true)
        }
      })
    },
    /**
     * 删除草稿
     */
    handleRemove() {
      this.$confirm({
        title: '温馨提示',
        content: '确定删除草稿？',
        onOk: () => {
          return projectImplementationPlan.remove({ id: this.id }).then((res) => {
            this.$message.success('删除成功！')
            // 关闭当前页
            this.$multiTab.close()
          })
        }
      })
    },
    /**
     * 提交表单
     */
    handleSubmit(statusCode) {
      let that = this
      that.setProcessConfig = null;
      let name = ['update', 'create', 'adjustment'][that.editModel - 1] // 根据操作切换url地址
      // 校验表单
      that.$refs.ruleForm.validate((e) => {
        if (e || statusCode === 0) {
          // 校验计划项表单
          if (this.form.planItems.length > 0) {
            for (let index in this.form.planItems) {
              let item = this.form.planItems[index] // 行数据源
              // 若分包商未进场，则设置班组也未进场
              if (item.subcontractorId === '-1') {
                // item.subcontractor = '分包单位未进场'
                // item.monitor = '分包单位未进场'
                item.monitorId = '-1'
              }
              let keys = {
                part: '样板部位',
                name: '样板名称',
                subcontractorId: '劳务单位',
                monitorId: '班组',
                makeDate: '计划制作时间',
                implPoints: '实施要点'
              } // 需要校验的对象
              for (let i in keys) {
                // 存在于校验对象，且表单值为空或不存在时提示
                if (!Object.keys(item).includes(i) || (Object.keys(item).includes(i) && !item[i])) {
                  this.$message.warning(`序号${Number(index) + 1}的${keys[i]}不能为空！`)
                  return
                }
              }
            }
          } else {
            this.$message.warning('计划项不能为空')
            return
          }
          statusCode === 0 && that.$refs.ruleForm.clearValidate()
          // 提交表单
          that.loading[statusCode] = true
          let form = that.$clone(that.form)
          form.statusCode = statusCode
          this.submitApprovalConfirm(statusCode == 1 ?this.processConfig : 6, (flag)=>{
            if(!flag) {
              that.loading[statusCode] = false
              return
            }
            projectImplementationPlan[name](form)
                    .then((res) => {
                      that.loading[statusCode] = false
                      that.$message.success(['保存', '提交'][statusCode] + '成功！')
                      if(statusCode*1===1) {
                        //提交时，返回id
                        that.businessId = res.data.businessId;
                        that.setProcessConfig = this.processConfig;
                        return
                      }else{
                        that.$multiTab.close()
                      }
                    })
                    .catch((res) => {
                      // that.$message.warning(['保存', '提交'][statusCode] + '失败!')
                      that.loading[statusCode] = false
                    })
          })

        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    }
  }
}
</script>
